package com.fjb.tool.im.client;

import com.fjb.tool.im.client.handler.MyClientInboundHandler;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

public class ImNettyClient {
	
	private MyClientInboundHandler clientHandler;
    
    public ImNettyClient(String nickName){
        this.clientHandler = new MyClientInboundHandler(nickName);
    }
	
    /**
     * @Description:TODO
     * @param host
     * @param port
     * void
     * @exception:
     * @author: hemiao
     * @time:2020年4月4日 下午6:55:59
     */
	public void connect(String host,int port) {
		
		// 创建一个 netty 工作线程池
		EventLoopGroup workGory = new NioEventLoopGroup();
		// 
		Bootstrap bootstrap = new Bootstrap();
		bootstrap.group(workGory)
		.channel(NioSocketChannel.class)
		.option(ChannelOption.SO_REUSEADDR,true)
		.handler(new ChannelInitializer<Channel>() {
			@Override
			protected void initChannel(Channel ch) throws Exception {
				System.out.println("initChannel");
				ChannelPipeline pipeline = ch.pipeline();
				pipeline.addLast(clientHandler);
			}	
		});
		try {
			ChannelFuture future = bootstrap.connect(host,port).sync();
			future.channel().close().sync();
			
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally {
			workGory.shutdownGracefully();
		}
	}
	
	public static void main(String[] args) {
		new ImNettyClient("hemiao").connect("127.0.0.1", 8080);
	}
}
